import { computed, reactive, Ref, ref } from 'vue'
import { useStore } from '/@/store'
import { geGaugetype, geMeasureList } from '/@/api/home/home'
import { getUser } from '/@/util/auth'
import { useRouter } from 'vue-router'

export function useClassify(query: any, fetchFlag: Ref<boolean>) {
  const store = useStore()
  const categoryOptions = reactive<any[]>([])
  const state = reactive<Record<any, any>>({
    loading: {}, //false
    finished: {}, //false
    refreshing: {}, //false
    pageSize: 10, //10
    currentPage: {}, //1
    total: {}, //0
    check: false,
  })
  const activeName = ref('')
  const ctr_user = JSON.parse(getUser())
  const itemListObj = reactive<Record<any, any>>({})
  const guestTenantId = '142417' //游客租户

  const userInfo = JSON.parse(localStorage.getItem('fock_user_data')!)

  geGaugetype().then((res) => {
    const data: any[] = res.data.data
    data.forEach((item) => {
      if (store.state.enterprise.includes(userInfo.tenantId)) {
        if (item.typeName == '专项测试') {
          categoryOptions.push(item)
        }
      } else {
        categoryOptions.push(item)
        state.loading[item.projectGaugeTypeId] = false
        state.finished[item.projectGaugeTypeId] = false
        state.refreshing[item.projectGaugeTypeId] = false
        state.currentPage[item.projectGaugeTypeId] = 1
        state.total[item.projectGaugeTypeId] = 0
      }
    })
    let gaugeTypeId: string

    if (query && query.projectGaugeTypeId !== undefined) {
      gaugeTypeId = query.projectGaugeTypeId as string
    } else {
      gaugeTypeId = categoryOptions[0].projectGaugeTypeId
    }

    activeName.value = gaugeTypeId

    if (gaugeTypeId) {
      const tenantId =
        ctr_user && ctr_user.tenantId ? ctr_user.tenantId : guestTenantId
      fetchFlag.value = true
      geMeasureList(1, 100, {
        gaugeTypeId: gaugeTypeId,
        tenantId: tenantId,
        status: 1,
      }).then((res) => {
        fetchFlag.value = false
        itemListObj[gaugeTypeId] = res.data.data.records
      })
    }
  })

  return {
    state,
    categoryOptions,
    activeName,
    ctr_user,
    itemListObj,
  }
}

export function useMoreInfo() {
  const fetchFlag = ref(true)

  return {
    fetchFlag,
    info: computed(() => (fetchFlag.value ? '加载中...' : '没有更多了')),
  }
}

export function useNavTo() {
  const router = useRouter()

  const onClickLeft = () => {
    router.push({
      name: 'Home',
      params: {},
    })
  }

  const onClickRight = () => {
    router.push({
      name: 'Me',
      params: {},
    })
  }

  return {
    onClickLeft,
    onClickRight,
  }
}
